package com.zjlp.im.netty.handler;

import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.*;

/**
 * Created by Administrator on 2016/12/8.
 */
public class DefaultHttpClientHandler extends SimpleChannelInboundHandler<Object> {
    private NioEventLoopGroup group;
    public DefaultHttpClientHandler(NioEventLoopGroup group){
        this.group=group;
    }
    /**
     * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     * <p>
     * Is called for each message of type {@link Object}.
     *
     * @param ctx the {@link io.netty.channel.ChannelHandlerContext} which this {@link io.netty.channel.SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof DefaultHttpResponse){
            System.out.println("接收到服务端返回的响应是"+ msg);
        }
        if (msg instanceof DefaultHttpContent){
            System.out.println("服务端返回的内容是:"+new String(ByteBufUtil.getBytes(((DefaultHttpContent) msg).content())));
            DefaultFullHttpRequest request=new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"/file/upload");
            request.content().writeBytes("客户端已经收到响应了，我要关闭客户端了！！".getBytes());
            ctx.writeAndFlush(request);
            ChannelFuture closeFuture=ctx.close();
            closeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()){
                        System.out.println("客户端关闭成功！！！");
                        group.shutdownGracefully();
                    }
                }
            });
        }

    }
}
